#  django
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
#  rest_framework
from rest_framework.views import APIView
from rest_framework.authentication import BasicAuthentication, BaseAuthentication
from rest_framework import exceptions
#  models
from user.models import UserInfo, UserToken
#  serializers
from user.serializers import UserInfoSerializer
#  认证

# Create your views here.

def md5(user):
    """
    对user取时间的MD5散列值
    """
    import hashlib
    import time
    ctime = str(time.time())
    m = hashlib.md5(bytes(str(user), encoding='utf-8'))
    m.update(bytes(ctime, encoding='utf-8'))
    return m.hexdigest()

class AuthView(APIView):
    #  获取token不需要认证
    authentication_classes = []

    def post(self, request, *args, **kwargs):

        ret = {'code': 1000, 'msg': None}
        try:
            #  验证用户是否存在并且密码是否正确
            user = request.data.get('username')
            pwd = request.data.get('password')
            obj = UserInfo.objects.filter(username=user,
                    password=pwd).first()
            print(user, pwd, obj)
            if not obj:
                ret['code'] = 1001
                ret['msg'] = "用户名或者密码错误"
            #  未登录创建token
            token = md5(user)
            UserToken.objects.update_or_create(user=obj,
                    defaults={'token': token})
            ret['token'] = token

        except Exception as err:
            ret['code'] = 1002
            ret['msg'] = "请求异常"
            print(err)

        return JsonResponse(ret)


class UserInfoView(APIView):
    USERINFO = {
        1:{
            'name': "molio",
            'age': 19,
            'gender': '男'
        },
        2:{
            'name': "lee",
            'age': 20,
            'gender': '男'
        },
        3:{
            'name': "yfc",
            'age': 18,
            'gender': '男'
        },
    }
    authentication_classes = [BasicAuthentication,]

    def get(self, request, *args, **kwargs):
        print(request.user)
        #  request.auth

        ret = {'code': 1000, 'msg': None, 'data': None}

        try:
            ret['data'] = self.USERINFO
        except Exception as err:
            print(err)

        return JsonResponse(ret)

